package com.yinzifan.seller.service;

import java.util.List;

import javax.annotation.PostConstruct;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Service;

import com.yinzifan.api.events.ProductStatusEvent;
import com.yinzifan.entity.Product;
import com.yinzifan.entity.enums.ProductStatus;

/**
 * @author Cin
 *
 */
@Service
public class ProductRpcService implements ApplicationListener<ContextRefreshedEvent>{
	@Autowired
	private ProductCache productCache;
	
	
	private static final Logger LOGGER = LoggerFactory.getLogger(ProductRpcService.class);
	private final String MQ_DESINATION= "Consumer.cache.VirtualTopic.PRODUCT_STATUS";
	
	public List<Product> findAll() {
		return productCache.readAllCache();
	}
	
	public Product findOne(String id) {
		Product product = productCache.readCache(id);
		if(product == null) {
			productCache.removeCache(id);
		}
		return product;
	}
	
	@PostConstruct
	public void test() {
		List<Product> result = findAll();
		LOGGER.info("rpc查询全部产品, 结果: {}", result);
	}

	@Override
	public void onApplicationEvent(ContextRefreshedEvent event) {
		List<Product> products = findAll();
		products.forEach(product -> {
			productCache.putCache(product);
		});
	}
	@JmsListener(destination=MQ_DESINATION)
	void updateCache(ProductStatusEvent event) {
		productCache.removeCache(event.getId());
		if(ProductStatus.IN_SELL.equals(event.getProductStatus())) {
			productCache.readCache(event.getId());
		}
	}
	
	
	
}
